package queuedemo;

import java.util.LinkedList;
import java.util.Queue;

public class MyStack {
  private Queue<Integer> queue1;
  private Queue<Integer> queue2;

    public MyStack() {
        this.queue1 = new LinkedList<>();
        this.queue2 = new LinkedList<>();
    }


//压入栈顶，找哪个队列不为空
    public void push(int x) {
if (empty()){
    queue1.offer(x);
}else {
    if (queue1.isEmpty()){
        queue2.offer(x);
    }else {
        queue1.offer(x);
    }
}
    }
//移除并且返回栈顶元素,offer()是放元素，poll取元素
    public int pop() {
        //看是否为空
if (empty()) return -1;
//如果第一个列表不为空
        if (!queue1.isEmpty()){
            int size=queue1.size()-1;
            while (size>0){
                queue2.offer(queue1.poll());
                size--;
            }
            return queue1.poll();
        }
        if (!queue2.isEmpty()){
            int size=queue2.size()-1;
            while (size>0){
                queue1.offer(queue2.poll());
                size--;
            }
            return queue2.poll();
        }
        return -1;
    }
//返回栈顶元素
    public int top() {
        if (empty()) return -1;
//如果第一个列表不为空
        if (!queue1.isEmpty()){
            int size=queue1.size()-1;
            while (size>0){
                queue2.offer(queue1.poll());
                size--;
            }
            int temp=queue1.poll();
            queue2.offer(temp);
            return temp;
        }
        if (!queue2.isEmpty()){
            int size=queue2.size()-1;
            while (size>0){
                queue1.offer(queue2.poll());
                size--;
            }

            return queue2.poll();
        }
        return -1;

    }

    public boolean empty() {
return queue1.isEmpty()&&queue1.isEmpty();
    }
}
